package com.mornd.gulimall.product.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @author: mornd
 * @dateTime: 2023/8/13 - 1:50
 *
 */

@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class CacheConfig {

    /*
        使用 spring cache
        1、导入依赖 spring-boot-starter-cache
        2、添加 @EnableCaching 否则缓存注解失效
        3、使用

        @Cacheable: Triggers cache population.  将数据保存到缓存
        @CacheEvict: Triggers cache eviction. 将数据从缓存删除
        @CachePut: Updates the cache without interfering with the method execution. 更新缓存，不影响方法执行
        @Caching: Regroups multiple cache operations to be applied on a method. 组合以上多个操作
        @CacheConfig: Shares some common cache-related settings at class-level. 在类级别共享缓存的相同配置
     */

    /**
     * cache配置
     * org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration.cacheManager
     * 覆盖更新 org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration#createConfiguration(org.springframework.boot.autoconfigure.cache.CacheProperties, java.lang.ClassLoader)
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
                .defaultCacheConfig();

        // key 序列化器
        config = config.serializeKeysWith(RedisSerializationContext.string().getKeySerializationPair());

        // 将 JdkSerializationRedisSerializer 默认value序列化器更换为 GenericJackson2JsonRedisSerializer
        config = config
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));

        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}
